package org.practice.springaichatmemory.config;

import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class OpenAiConfig {

    @Value("${spring.ai.openai.api-key}")
    private String apiKey;

    @Value("${spring.ai.openai.base-url}")
    private String baseUrl;

    @Value("${spring.ai.openai.chat.options.model}")
    private String chatModel;
    @Bean
    @Primary
    public OpenAiApi openAiApi() {
        return new OpenAiApi(baseUrl, apiKey);
    }

    @Bean
    @Primary
    public OpenAiChatModel openAiChatModel(OpenAiApi openAiApi) {
        // 显式使用配置文件中的选项
        OpenAiChatOptions options = OpenAiChatOptions.builder()
                .model(chatModel)  // 使用配置文件中指定的模型
                .build();
        return new OpenAiChatModel(openAiApi, options);
    }
    
    @Bean
    public ChatMemory chatMemory() {
        // 使用InMemoryChatMemory，虽然没有直接的消息数量限制，但可以与我们自定义的清理服务配合使用
        return new InMemoryChatMemory();
    }
}